<?php

namespace console\controllers;

use Yii;
use yii\db\Query;
use common\components\Myhelpers;
use common\models;
use yii\helpers\ArrayHelper;


class SmsController extends CController
{
    public $num = 10;// 每次发送多少条

    /**
	 * 测试任务
	 * @return [type] [description]
	 */
    public function actionIndex()
    {
        $t1 = microtime(true); //运行时间
        $db = Yii::$app->db;
        echo "send sms ...".date('Y-m-d H:i:s')."\n";

        do {
            //获取5分钟前的数据 发送短信
            $expire = date('Y-m-d H:i:s', time() - 5 * 60);
            $sql = "SELECT id,user_id,tel,type,tpl_id,var_json FROM `sms` WHERE  `send_status` = 1 AND `auto_send` = 2 AND `create_time` >='$expire' ORDER BY `weight` DESC, `id` ASC LIMIT  ".$this->num;
//            $sql = "SELECT id,user_id,tel,type,tpl_id,var_json FROM `sms` WHERE  id=2";
            $list = $db->createCommand($sql)->queryAll();
            //没有数据返回
            if (!empty($list)) {
                //需要把状态更改掉，防止重复发送
                $this->sendProcess($list);

                foreach ($list as $key => $sms) {
                    //发送短信
                    $res = [
                        'result'=>false,
                        'message'=>'error',
                    ];//初始化
                    if ($sms['type'] == 1 || $sms['type'] == 0) {
                        $res = Myhelpers::sendSms(
                            $sms['tel'],
                            array (
                                'templateId' => $sms['tpl_id'],
                                'vars' => $sms['var_json'],
                            )
                        );//返回结果是数组

                    }
                    var_dump($res);
                    //根据返回状态重叠发送状态
                    if ($res['result']) {
                        //发送成功
                        $this->setStatus($sms['id'], 3);
                    } else {
                        //发送失败
                        $this->setStatus($sms['id'], 4, $res['message']);
                    }
                }
            }

            //判断执行时间，超过59就停止运行
            sleep(1);
            $t2 = microtime(true);
            $t = round($t2 - $t1, 3); //消耗多少秒
            echo $t."\n";
        } while($t <= 59);

        //返回0或者1
        return 0;
    }

    //设置为处理中, list 为sms结果集
    public function sendProcess($list){
        if (!empty($list)) {
            $db = Yii::$app->db;
            //需要把状态更改掉，防止重复发送
            $ids = ArrayHelper::getColumn($list,'id');
            $ids = implode($ids, ',');
            $sql = "UPDATE `sms` SET `send_status`=2  WHERE id IN ($ids) ";
            //执行sql
            $db->createCommand($sql)->execute();
        }
    }

    /**
     * @param $id sms表id
     * @param int $send_status 发送状态：3成功；4失败
     * @param string $remark 备注：成功不用备注，失败需要备注下失败原因
     * @return bool
     * @throws \yii\db\Exception
     */
    public function setStatus($id, $send_status = 3, $remark=''){
        if (!$id || !$send_status) {
            return false;
        }
        $db = Yii::$app->db;
        $update_time = date('Y-m-d H:i:s', time());
        if( !$remark ){
            $sql = "UPDATE `sms` SET `send_status`=$send_status, update_time='$update_time'  WHERE id=".$id;
        }else{
            $sql = "UPDATE `sms` SET `send_status`=$send_status, update_time='$update_time',remark='$remark'  WHERE id=".$id;
        }
        $db->createCommand($sql)->execute();
    }

//    public function actionSend($phone) {
//
//        $url = 'http://sendcloud.sohu.com/smsapi/send';
//        $smskey = 'Mz6ldyNHbjZ8aMqODLnQHAdaUc03IOJr';
//        $sign_name = 'sms_reg';
//        $code = rand(100000,999999);
//        //$phone = "15868152817";
//
//        $request['smsUser'] = 'tianpin_sms';
//        $request['templateId'] = '1669';
//        $request['msgType'] = '0';
//        $request['phone'] = $phone;
//        $request['vars'] = json_encode(["%".$sign_name."%" => $code]);
//
//        $sParamStr = "";
//        ksort($request);
//        foreach ($request as $sKey => $sValue) {
//            $sParamStr .= $sKey . '=' . $sValue . '&';
//        }
//
//        $sParamStr = trim($sParamStr, '&');
//        $sSignature = md5($smskey."&".$sParamStr."&".$smskey);
//
//        $request['signature'] = $sSignature;
//
//        $data = http_build_query($request);
//        //echo $data;
//
//        $options = array(
//            'http' => array(
//                'method' => 'POST',
//                'header' => 'Content-Type:application/x-www-form-urlencoded',
//                'content' => $data
//
//        ));
//        //请求之前插入表中
//        $sms['user_id'] = 1;
//        $sms['tel'] = $request['phone'];
//        $sms['auto_send'] = 2;
//        $sms['tpl_id'] = $request['templateId'];
//        $sms['create_time'] = date('Y-m-d H:i:s');
//
//        $sms_log = Yii::$app->db->createCommand()->insert('sms',$sms)->execute();
//
//        if($sms_log){
//        	$context  = stream_context_create($options);
//	        $result = file_get_contents($url, FILE_TEXT, $context);
//
//	        echo $result;
//	        /*$res = json_encode($result,true);
//	        $result = $res['result'];
//	        $statusCode = $res['statusCode'];
//	        $message = $res['message'];*/
//        }else{
//        	echo 'insert failed';
//        }
//	}


}